package com.baiku.sanhos.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginAfter implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 获取所有cookie
        Cookie[] cookies = request.getCookies();
        // 判断是否有token的cookie
        boolean hasTokenCookie = false;

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    hasTokenCookie = true;
                    break;
                }
            }
        }

        // 如果有token的cookie，表示用户已登录，放行
        if (hasTokenCookie) {
            log.debug("用户已登录，继续处理后续逻辑。");
        } else {
            // 用户未登录，进行重定向到登录页面或其他处理
            log.debug("用户未登录，将重定向到登录页面。");
            response.sendRedirect("/login.html");
        }
    }
}
